package hotel.compare.oversea.config.DataSource;

import com.zaxxer.hikari.HikariDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import tk.mybatis.spring.annotation.MapperScan;

import javax.sql.DataSource;

/**
 * 携程数据源
 * @author Zhang·JZ
 */
@Configuration
@MapperScan(basePackages = "hotel.compare.oversea.mapper.switchs", sqlSessionFactoryRef = "switchsSqlSessionFactory")
public class SwitchsDataSourceConfig {
	@Value("${switchs.datasource.driver-class-name}")
	private String driverClassName;

	@Value("${switchs.datasource.url}")
	private String url;

	@Value("${switchs.datasource.username}")
	private String username;

	@Value("${switchs.datasource.password}")
	private String password;

	@Bean(name = "switchsDataSource")
	public DataSource dataSource() {
		HikariDataSource dataSource = new HikariDataSource();
		dataSource.setDriverClassName(this.driverClassName);
		dataSource.setJdbcUrl(url);
		dataSource.setUsername(this.username);
		dataSource.setPassword(this.password);
		return dataSource;
	}

	/**
	 * application.yml配置不生效，由于@order配置顺序不同，配置无法及时生效需手动注解
	 * @return
	 */
	/*@Bean
	@ConfigurationProperties(prefix = "mybatis.configuration")
	public org.apache.ibatis.session.Configuration globalConfiguration(){
		return new org.apache.ibatis.session.Configuration();
	}*/

	@Bean(name = "switchsSqlSessionFactory")
	public SqlSessionFactory sqlSessionFactory(@Qualifier("switchsDataSource") DataSource dataSource) throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
		configuration.setMapUnderscoreToCamelCase(true);
		bean.setConfiguration(configuration);
		bean.setMapperLocations(
				new PathMatchingResourcePatternResolver().getResources("classpath*:/hotel/compare/mapper/switchs/*Mapper.xml"));
		return bean.getObject();
	}

	@Bean(name = "switchsTransactionManager")
	public DataSourceTransactionManager transactionManager(@Qualifier("switchsDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "switchsSqlSessionTemplate")
	public SqlSessionTemplate testSqlSessionTemplate(
			@Qualifier("masterSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}
}
